package com.sinothk.special.buyer.userblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.special.buyer.userblog.entity.UserBlog;
import com.sinothk.special.buyer.userblog.entity.UserBlogVisitor;
import com.sinothk.special.buyer.userblog.mapper.UserBlogMapper;
import com.sinothk.special.buyer.userblog.mapper.UserBlogVisitorMapper;
import com.sinothk.special.buyer.userblog.service.IUserBlogVisitorService;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description: 个人博客访问者
 * @Author: Liangyt
 * @Date: 2022-06-06
 * @Version: V1.0
 */
@Service
public class UserBlogVisitorServiceImpl extends ServiceImpl<UserBlogVisitorMapper, UserBlogVisitor> implements IUserBlogVisitorService {

    @Resource
    private UserBlogMapper userBlogMapper;
    @Resource
    private UserBlogVisitorMapper userBlogVisitorMapper;

    @Override
    public void addVisitHistory(String blogId) throws Exception {
        UserBlog userBlog = userBlogMapper.selectById(blogId);
        if (userBlog == null) throw new Exception("信息不存在");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        LambdaQueryWrapper<UserBlogVisitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserBlogVisitor::getBlogId, blogId).eq(UserBlogVisitor::getVisitorId, loginUser.getId());
        UserBlogVisitor userBlogVisitorDB = userBlogVisitorMapper.selectOne(wrapper);
        if (userBlogVisitorDB == null) {
            UserBlogVisitor userBlogVisitor = new UserBlogVisitor();
            userBlogVisitor.setBlogId(blogId);
            userBlogVisitor.setVisitorId(loginUser.getId());
            userBlogVisitorMapper.insert(userBlogVisitor);
        }else{
            userBlogVisitorMapper.updateById(userBlogVisitorDB);
        }
    }
}
